﻿using System;
using System.Data;
using System.Threading;
using System.Windows.Forms;
using ChinaDynastyTours.Assets;
using ChinaDynastyTours.Assets.DataSet;
using ChinaDynastyTours.Controls;
using ChinaDynastyTours.Helpers;
using ChinaDynastyTours.Models;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;

namespace ChinaDynastyTours.Views
{
    public partial class LocalPlanScheduleForm : DevExpress.XtraEditors.XtraForm
    {
        public DataView _TourGroupDataTable { get; set; }
        public int _Position { get; set; }
        private DataTable _ScheduleData = null;

        private int _currentPageNumber = 1; //当前页号
        private int _totalPageNumbers;  //总页号
        private string _firstlocalPlanScheduleID = "";//第一行本地行程ID
        //private string[] _providerNameAndID;

        //private string _Remark = "";

        public LocalPlanScheduleForm(DataView tourGroupDataTable)//, int rowID)
        {
            InitializeComponent();
        
            _TourGroupDataTable = tourGroupDataTable;
            //_Position = rowID;
            //_Remark = _TourGroupDataTable[0]["LocalRemark"].ToString();
        }
    
 
        #region 窗口初始化

        private void LocalPlanScheduleForm_Load(object sender, EventArgs e)
        {
            //_providerNameAndID = BaseInfoCtrl.GetProviderNameAndID(Thread.CurrentPrincipal.Identity.Name);
            //初始化团基本信息显示
            InitGui();
            this.BindingContext[_TourGroupDataTable].Position = _Position;

            //初始化计划内容
            //LoadScheduleGridViewData();
            UpdateButtonStatus();
            LoadSelectPage(1);
            _firstlocalPlanScheduleID = scheduleGridView.GetRowCellValue(0, "LocalPlanScheduleID").ToString();

            #region 团状态按钮处理

            DataRowView drv = (BindingContext[_TourGroupDataTable].Current as DataRowView);
            switch (TeamGroupCtrl.GetTourGroupState(lblTourGroupID.Text))
            {
                case TeamStateEnum.审核:
                case TeamStateEnum.终结:
                    //btnAdd.Enabled = false;
                    //btnDelete.Enabled = false;
                    btnRestaurant.Enabled = false;
                    mbLocalRemark.Enabled = false;
                    scheduleGridContextMenu.Enabled = false;
                    scheduleGridView.OptionsBehavior.Editable = false;
                    break;
                default:
                    break;
            }
            #endregion
        }

        //计划行程数据加载
        private void LoadSelectPage(int pageNumber)
        {
            //提供‘城市’选择         
            //StartAndEndCityEdit.DataSource = BaseInfoCtrl.GetCityData();

            _ScheduleData = LocalTeamGroupCtrl.GetLocalPlanSchedule(lblTourGroupID.Text, ApplicationHelper.CurrentLoginProviderNameAndID[1], pageNumber);
            scheduleGridControl.DataSource = _ScheduleData;

            //赋值CiceroniID并引发tbCiceroni_EditValueChanged事件
            //tbCiceroni.EditValue = LocalTeamGroupCtrl.GetLocalPlanScheduleCiceroniIDByPageNumber(lblTourGroupID.Text, pageNumber, ApplicationHelper.CurrentLoginProviderNameAndID[1]);
            

            //为行程计划网格‘视图’注册数据更新事件
            _ScheduleData.RowDeleted += new DataRowChangeEventHandler(Table_RowDeleted);
            _ScheduleData.RowChanged += new DataRowChangeEventHandler(Table_RowChanged);

            //tbOperationNumber.DataBindings.Clear();
            //tbOperationNumber.DataBindings.Add("EditValue", _ScheduleData, "OperationNumber");

        
            UpdateButtonStatus();
        }

        /*
        private void tbCiceroni_EditValueChanged(object sender, EventArgs e)
        {
            if (tbCiceroni.EditValue == DBNull.Value)
            {
                tbOpCode.EditValue = "";
                return;
            }
            string ciceroniId = tbCiceroni.EditValue.ToString();
            tbOpCode.EditValue = BaseInfoCtrl.GetCiceroniPhoneById(ciceroniId);
            LocalTeamGroupCtrl.UpdateLocalTourGroupScheduleCiceroniData(lblTourGroupID.Text,_currentPageNumber,ciceroniId,tbCiceroni.Text,tbOpCode.Text);
        }
         */
        //初始化界面内容
        private void InitGui()
        {
            //团状态信息
            lblTourGroupID.DataBindings.Add("Text", _TourGroupDataTable, "TourgroupID");
            lblTourGroupState.DataBindings.Add("Text", _TourGroupDataTable, "TourgroupState");


            tbCountry.DataBindings.Add("EditValue", _TourGroupDataTable, "Country");
            lblCountryCode.DataBindings.Add("Text", _TourGroupDataTable, "CountryCode");
            tbStartDate.DataBindings.Add("EditValue", _TourGroupDataTable, "StartDate");
            tbEndDate.DataBindings.Add("EditValue", _TourGroupDataTable, "EndDate");
            tbNightNum.DataBindings.Add("EditValue", _TourGroupDataTable, "StayOver");
            tbAdultNum.DataBindings.Add("EditValue", _TourGroupDataTable, "AdultNum");
            tbChildNum.DataBindings.Add("EditValue", _TourGroupDataTable, "ChildNum");
            tbTourgroupName.DataBindings.Add("EditValue", _TourGroupDataTable, "TourgroupName");
            cbGuesttype.DataBindings.Add("EditValue", _TourGroupDataTable, "Guesttype");
            cbServicetype.DataBindings.Add("EditValue", _TourGroupDataTable, "Servicetype");
            cbTourgrouptype.DataBindings.Add("EditValue", _TourGroupDataTable, "Tourgrouptype");
            tbAccompanyNum.DataBindings.Add("EditValue", _TourGroupDataTable, "AccompanyNum");
            tbCustomerCode.DataBindings.Add("EditValue", _TourGroupDataTable, "CustomerCode");
            lblCustomerName.DataBindings.Add("Text", _TourGroupDataTable, "CustomerName");
            cbOwnerA.DataBindings.Add("EditValue", _TourGroupDataTable, "OwnerA");
            cbOwnerB.DataBindings.Add("EditValue", _TourGroupDataTable, "OwnerB");
            ckHasGuide.DataBindings.Add("Checked", _TourGroupDataTable, "HasGuide");
            tbBuildGroupDate.DataBindings.Add("EditValue", _TourGroupDataTable, "BuildGroupDate");
            mbLocalRemark.DataBindings.Add("EditValue", _TourGroupDataTable, "LocalRemark");//此备注通过绑定显示数据，通过‘关闭’按钮保存更新数据
            
            string rowState = _TourGroupDataTable[0]["LocalTourgroupRowState"].ToString();//.Rows[_Position]["LocalTourgroupRowState"].ToString();
            tbLocalTourgroupRowState.Checked = (rowState == "2");

            /*
            tbCiceroni.Properties.DataSource = GuideArrangeCtrl.GetGuideInfoForPrint(lblTourGroupID.Text);//BaseInfoCtrl.GetCiceroniNameData("");
            tbCiceroni.Properties.DisplayMember = "CiceroniName";
            tbCiceroni.Properties.ValueMember = "CiceroniID";  
             */
            tbOperationNumber.EditValue = LocalTeamGroupCtrl.GetOperationNumberForTravel(lblTourGroupID.Text,ApplicationHelper.CurrentLoginProviderNameAndID[1]);
        }
        #endregion

        #region 计划行程数据变化后的后台处理
        void Table_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Change || e.Action == DataRowAction.ChangeCurrentAndOriginal || e.Action == DataRowAction.ChangeOriginal)
            {

                ProvidersPlanSchedule schedule = new ProvidersPlanSchedule();
                schedule.TourgroupID = this.lblTourGroupID.Text;
                schedule.Date = DateTime.Parse(e.Row["Date"].ToString()).ToString("yyyy-MM-dd");
                schedule.Time = DateTime.Parse(e.Row["Time"].ToString()).ToString("HH:mm:ss");
                schedule.StayOver = int.Parse(e.Row["StayOver"].ToString());
                schedule.Journeytype = e.Row["Journeytype"].ToString();
                schedule.StartCity = e.Row["StartCity"].ToString();
                schedule.DestinationCity = e.Row["DestinationCity"].ToString();
                schedule.TrafficType = e.Row["TrafficType"].ToString();
                schedule.Traffic = e.Row["Traffic"].ToString();
                schedule.TravelAgencyID = int.Parse(e.Row["TravelAgencyID"].ToString());
                schedule.TravelAgencyName = e.Row["TravelAgencyName"].ToString();
                schedule.Reception = e.Row["Reception"].ToString();
                schedule.TicketType = e.Row["TicketType"].ToString();
                schedule.Context = e.Row["Context"].ToString();
                schedule.Dining = e.Row["Dining"].ToString();
                schedule.Hotel = e.Row["Hotel"].ToString();
                schedule.HotelID = int.Parse(e.Row["HotelID"].ToString());
                schedule.OperationNumber = e.Row["OperationNumber"].ToString();
                //schedule.CiceroniID = e.Row["CiceroniID"] == DBNull.Value ? 0 : int.Parse(e.Row["CiceroniID"].ToString());
                //schedule.CiceroniName = e.Row["CiceroniName"].ToString();
                //schedule.Phone = e.Row["Phone"].ToString();

                schedule.LocalPlanScheduleID = int.Parse(e.Row["LocalPlanScheduleID"].ToString());

                LocalTeamGroupCtrl.UpdateLocalTourGroupSchedule(schedule);
            }
        }

        private void Table_RowDeleted(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Delete)
            {
                string localPlanScheduleID = e.Row["LocalPlanScheduleID", DataRowVersion.Original].ToString();
                if (localPlanScheduleID == "")
                    return;

                int scheduleID = int.Parse(localPlanScheduleID);
                
                //将已有预订挪至第一天的行程中
                //EntertainmenRestaurantOrderCtrl.UpdateEntertainmenRestauranLocalScheduleID(localPlanScheduleID, _firstlocalPlanScheduleID);
                //VehicleOrderCtrl.UpdateVehicleLocalScheduleID(localPlanScheduleID, _firstlocalPlanScheduleID);

            
                //删除行程计划数据
                LocalTeamGroupCtrl.DeleteLocalTourGroupSchedule(scheduleID);
            }
            //刷新
            //LoadProvidersListData();
        }

        #endregion

        #region 右键菜单处理 娱乐(演出门票、景点门票)、餐厅、汽车

        private void mnuRestaurant_Click(object sender, EventArgs e)
        {
            RestaurantOrderForm enterRestOrderForm = new RestaurantOrderForm()
            { 
                _TourGroupID=lblTourGroupID.Text,
                _LocalPlanScheduleDate = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "Date").ToString(),
                _LocalPlanScheduleID = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "LocalPlanScheduleID").ToString(),
                _TourGroupScheduleID = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "TourGroupScheduleID").ToString(),
                _LoginProviderID = ApplicationHelper.CurrentLoginProviderNameAndID[1]
                //_AccompanyNum = tbAccompanyNum.EditValue == DBNull.Value ? 0 : int.Parse(tbAccompanyNum.EditValue.ToString())
            };
            enterRestOrderForm.ShowDialog(this);
            
            //string diningContext  = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "Dining").ToString();
            scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "Dining", enterRestOrderForm._returnRestaurant);
            //刷新
            //LoadProvidersListData();
        }



        #endregion

        #region 窗口底部系列按钮事件处理

        #region 分页处理

        private void UpdateButtonStatus()
        {
            _totalPageNumbers = LocalTeamGroupCtrl.GetLocalPlanSchedulePageNumbers(lblTourGroupID.Text);

            btnPrevPage.Enabled = !(_currentPageNumber == 1);
            btnNextPage.Enabled = !(_currentPageNumber == _totalPageNumbers);
            llbCurrentPage.Text = string.Format("第{0}页/共{1}页", _currentPageNumber, _totalPageNumbers);
        }
        private void btnCopyCurrentPage_Click(object sender, EventArgs e)
        {
            string tourgroupName = TeamGroupCtrl.GetTeamGroupNameById(lblTourGroupID.Text);

            //获取当前行程计划列表中的信息
            foreach (DataRow dr in _ScheduleData.Rows)
            {
                ProvidersPlanSchedule entity = new ProvidersPlanSchedule()
                {
                    Date = dr["Date"].ToString(),
                    Time = dr["Time"].ToString(),
                    Context = dr["Context"].ToString(),
                    StartCity = dr["StartCity"].ToString(),
                    DestinationCity = dr["DestinationCity"].ToString(),
                    Dining = "",
                    Journeytype = dr["Journeytype"].ToString(),
                    Reception = dr["Reception"].ToString(),
                    StayOver = int.Parse(dr["StayOver"].ToString()),
                    TicketType = dr["TicketType"].ToString(),
                    TourGroupScheduleID = int.Parse(dr["TourGroupScheduleID"].ToString()),
                    Traffic = dr["Traffic"].ToString(),
                    TrafficType = dr["TrafficType"].ToString(),
                    TravelAgencyID = int.Parse(dr["TravelAgencyID"].ToString()),
                    TravelAgencyName = dr["TravelAgencyName"].ToString(),
                    Hotel = dr["Hotel"].ToString(),
                    HotelID = int.Parse(dr["HotelID"].ToString()),
                    Seat = dr["Seat"].ToString(),
                    TourgroupID = dr["TourgroupID"].ToString(),
                    PageNumber = _totalPageNumbers + 1,//总页号加1
                    OwnerProviderID=ApplicationHelper.CurrentLoginProviderNameAndID[1]
                };
                LocalTeamGroupCtrl.CreateLocalTourGroupSchedule(entity);
            }
            //加载新建页内容
            _currentPageNumber = _totalPageNumbers + 1;
            LoadSelectPage(_currentPageNumber);
            //LoadProvidersListData();
        }
        private void btnPrevPage_Click(object sender, EventArgs e)
        {
            LoadSelectPage(--_currentPageNumber);
            //LoadProvidersListData();
        }

        private void btnNextPage_Click(object sender, EventArgs e)
        {
            LoadSelectPage(++_currentPageNumber);
            //LoadProvidersListData();
            
        }        
        #endregion


        private void btnPreviewAndPrint_Click(object sender, EventArgs e)
        {
            SimpleButton btn = sender as SimpleButton;

            LocalPlanScheduleDataSet scheduleDs = new LocalPlanScheduleDataSet();

            //获取对应团信息，填充到打印数据集中
            DataTable dtTourgroup = TeamGroupCtrl.GetTeamGroupDataForSchedulePrint(lblTourGroupID.Text);

            //scheduleDs.Tables["Team"].ImportRow((BindingContext[_TourGroupDataTable].Current as DataRowView).Row);
            foreach (DataRow dr in dtTourgroup.Rows)
            {
                scheduleDs.Tables["Team"].ImportRow(dr);
                //为打印出各地接社的操作号，这里将团号替换为‘操作号’
                scheduleDs.Tables["Team"].Rows[0]["TourgroupID"] = LocalTeamGroupCtrl.GetOperationNumberForTravel(lblTourGroupID.Text, ApplicationHelper.CurrentLoginProviderNameAndID[1]);
            }

            DataTable dtTravelAgence = BaseInfoCtrl.GetProviderTableDataByID(ApplicationHelper.CurrentLoginProviderNameAndID[1]);
            foreach (DataRow dr in dtTravelAgence.Rows)
            {
                scheduleDs.Tables["Provider"].ImportRow(dr);
            }


            //获取对应行程信息，填充到打印数据集中
            DataTable dtSchedule = LocalTeamGroupCtrl.GetLocalPlanScheduleForPrint(lblTourGroupID.Text, _currentPageNumber, ApplicationHelper.CurrentLoginProviderNameAndID[1]);
            foreach (DataRow dr in dtSchedule.Rows)
            {
                dr["Date"] = DateTime.Parse(dr["Date"].ToString()).ToString("yy-MM-dd ddd");
                dr["Time"] = DateTime.Parse(dr["Time"].ToString()).ToString("HH:mm");
                scheduleDs.Tables["LocalPlanSchedule"].ImportRow(dr);
            }

            //获取对应导游信息，填充到打印数据集中
            DataTable dtGuide = GuideArrangeCtrl.GetGuideInfoForPrint(lblTourGroupID.Text);
            GuideDataSet guideDs = new GuideDataSet();
            foreach (DataRow dr in dtGuide.Rows)
            {
                dr["StartDate"] = DateTime.Parse(dr["StartDate"].ToString()).ToString("yyyy-MM-dd HH:mm");
                guideDs.Tables["Ciceroni"].ImportRow(dr);
            }


            //获取对应餐厅信息，填充到打印数据集中
            DataTable dtProvider = RestaurantOrderCtrl.GetRestaurantInfoForPrint(lblTourGroupID.Text);
            ProviderDataSet providerDs = new ProviderDataSet();
            foreach (DataRow dr in dtProvider.Rows)
            {
                providerDs.Tables["Provider"].ImportRow(dr);
            }

            LocalPlanScheduleReport rpt = new LocalPlanScheduleReport();
            TravelAgentReport providersubrpt = new TravelAgentReport();
            GuideReport guidesubrpt = new GuideReport();

            rpt.DataSource = scheduleDs;
            providersubrpt.DataSource = providerDs;
            guidesubrpt.DataSource = guideDs;
            rpt.GuideSubreport.ReportSource = guidesubrpt;
            rpt.ProviderSubreport.ReportSource = providersubrpt;

            if (btn.Equals(btnPreview))
                rpt.ShowPreviewDialog();
            else
                rpt.PrintDialog();
        }

        private void btnRemark_Click(object sender, EventArgs e)
        {
            panelRemark.Visible = true;
        }

        private void btnRemarkClose_Click(object sender, EventArgs e)
        {
            TeamGroupCtrl.UpdateTourGroupLocalRemark(lblTourGroupID.Text, mbLocalRemark.Text);
            panelRemark.Visible = false;
        }

        private void btnGuest_Click(object sender, EventArgs e)
        {
            GuestListForm guestListForm = new GuestListForm(lblTourGroupID.Text);
            guestListForm.ShowDialog(this);
        }
        private void btnGuidPlan_Click(object sender, EventArgs e)
        {
            GuidePlanForm guidePlanForm = new GuidePlanForm()
            {
                _TourGroupID = lblTourGroupID.Text,
                _TourgroupStartDate = DateTime.Parse(tbStartDate.EditValue.ToString()),
                _TourgroupEndDate = DateTime.Parse(tbEndDate.EditValue.ToString()),
            };
            guidePlanForm.ShowDialog(this);
        }
        
        private void btnBill_Click(object sender, EventArgs e)
        {
            //判断是否允许保障，两个条件1、大行程中要求安排导游而没安排，不允许报账；
            //if (BillCtrl.EnableSubmitExpenseBillDataForGuideArrange(lblTourGroupID.Text) == false)
            //{
            //    MessageBox.Show("存在要求安排导游而没有安排的情况，请安排后再填写账单", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}

            //2、大行程计划中安排了除‘早’或“”外的餐厅要求（如午晚、午、早午晚等），且本地行程中（Sch_ProvidersPlanSchedule）存在没有安排的，则不能报账
            if (BillCtrl.EnableSubmitExpenseBillDataForDiningArrange(lblTourGroupID.Text) == false)
            {
                MessageBox.Show("存在要求安排餐厅而没有安排的情况，请安排后再填写账单", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            string expenseID = ExpensesCtrl.GetExpenseIDForBill(lblTourGroupID.Text, ApplicationHelper.CurrentLoginProviderNameAndID[1]);
            string expenseStatus = ExpensesCtrl.GetExpenseStatusForBill(lblTourGroupID.Text, ApplicationHelper.CurrentLoginProviderNameAndID[1]);
            if (expenseID != "" && expenseStatus != "")
            {
                BillForm billForm = new BillForm();
                billForm._TourgroupID = lblTourGroupID.Text;
                billForm._ExpenseID = expenseID;
                billForm._ExpenseStatus = expenseStatus;
                billForm._CurrentDisplaySchedulePageNumber = _currentPageNumber;
                billForm.ShowDialog(this);
            }
            else
                MessageBox.Show("此团没有本地接社的费用预算！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

        private void tbLocalTourgroupRowState_CheckedChanged(object sender, EventArgs e)
        {
            if (tbLocalTourgroupRowState.Checked)//团已处理
                TeamGroupCtrl.UpdateTourGroupLocalTourgroupRowState(lblTourGroupID.Text, 2);
            else//去掉则置为团计划已经拷贝过来
                TeamGroupCtrl.UpdateTourGroupLocalTourgroupRowState(lblTourGroupID.Text, 1);
        }

        #endregion

        #region 行程计划GridView事件处理

        private void StartAndEndCityEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            //暂时屏蔽，用LookUpEdit提供的城市的选择方式

            DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
            CitySelectedToolForm city = new CitySelectedToolForm();

            if (city.ShowDialog(this) == DialogResult.OK)
                btnEdit.EditValue = city.ReturnCityName;

        }

        private void TrafficEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            string TrafficType = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, scheduleGridView.Columns["TrafficType"]).ToString();
            //string localPlanScheduleId = scheduleGridView.GetDataRow(scheduleGridView.FocusedRowHandle)["LocalPlanScheduleID"].ToString();

            if (string.IsNullOrEmpty(TrafficType))
            {

                MessageBox.Show("您还没有选择交通工具类型！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
            switch (EnumHelper.Traffic_Str2Enum(TrafficType, true))//CommonEnum.GetTrafficType(TrafficType))
            {
                case TrafficTypeEnum.飞机:
                    FlightOrderForm flightOrderForm = new FlightOrderForm()
                    {
                        _StartCity = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, scheduleGridView.Columns["StartCity"]).ToString(),
                        _EndCity = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, scheduleGridView.Columns["DestinationCity"]).ToString(),
                    };
                    if (flightOrderForm.ShowDialog(this) == DialogResult.OK)//设置各项返回值到表格中
                    {
                        btnEdit.EditValue = flightOrderForm._FlightCode;
                        //scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "StartCity", flightOrderForm._StartCity);
                        //scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "DestinationCity", flightOrderForm._EndCity);
                        string journeyType = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "Journeytype").ToString();
                        switch (EnumHelper.Journey_Str2Enum(journeyType, true))
                        {
                            case JourneyTypeEnum.入境:
                            case JourneyTypeEnum.抵:
                                scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "Time", flightOrderForm._EndTime);
                                break;
                            case JourneyTypeEnum.离境:
                            case JourneyTypeEnum.离:
                                scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "Time", flightOrderForm._StartTime);
                                break;
                            default:
                                break;
                        }
                    }
                    break;
                case TrafficTypeEnum.火车:
                    TrainOrderForm trainOrderForm = new TrainOrderForm()
                    {
                        _StartCity = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, scheduleGridView.Columns["StartCity"]).ToString(),
                        _EndCity = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, scheduleGridView.Columns["DestinationCity"]).ToString(),
                    };
                    if (trainOrderForm.ShowDialog(this) == DialogResult.OK)//设置各项返回值到表格中
                    {
                        btnEdit.EditValue = trainOrderForm._TrainCode;
                        //scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "StartCity", trainOrderForm._StartCity);
                        //scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "DestinationCity", trainOrderForm._EndCity);
                        string journeyType = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "Journeytype").ToString();
                        switch (EnumHelper.Journey_Str2Enum(journeyType, true))
                        {
                            case JourneyTypeEnum.入境:
                            case JourneyTypeEnum.抵:
                                scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "Time", trainOrderForm._EndTime);
                                break;
                            case JourneyTypeEnum.离境:
                            case JourneyTypeEnum.离:
                                scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "Time", trainOrderForm._StartTime);
                                break;
                            default:
                                break;
                        }
                    }
                    break;
                case TrafficTypeEnum.汽车:
                    MessageBox.Show("预留调用实时的‘汽车’服务信息！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
                default:
                    MessageBox.Show("您选择的交通工具类型目前不被支持！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
            }

        }

        private void TravelAgencyNameEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            string localPlanScheduleId = scheduleGridView.GetDataRow(scheduleGridView.FocusedRowHandle)["LocalPlanScheduleID"].ToString();
            TravelSelectedToolForm travelForm = new TravelSelectedToolForm()
            {
                _TourGroupID = lblTourGroupID.Text,
                _TourGroupState = lblTourGroupState.Text,
                _TourGroupScheduleID = int.Parse(localPlanScheduleId)
            };
            if (travelForm.ShowDialog(this) == DialogResult.OK)
            {
                DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
                btnEdit.EditValue = travelForm.ReturnTravelAgencyName;
                scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "TravelAgencyID", travelForm.ReturnTravelAgencyID);
                scheduleGridView.SetRowCellValue(scheduleGridView.FocusedRowHandle, "Reception", travelForm.ReturnContact);
            }
        }

        #endregion

        private void LocalPlanScheduleForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //激发行程计划的GrideView数据更新
            if (scheduleGridView.FocusedRowModified)
                scheduleGridView.FocusedRowHandle = scheduleGridView.FocusedRowHandle == 0 ? 1 : 0;
            //if (providerListGridView.FocusedRowModified)
            //    providerListGridView.FocusedRowHandle = providerListGridView.FocusedRowHandle == 0 ? 1 : 0;
        }

        private void scheduleGridView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            //LoadProvidersListData();
            //激活备注Tab页
            tourGroupScheduleTabControl_SelectedPageChanged(tourGroupScheduleTabControl, new DevExpress.XtraTab.TabPageChangedEventArgs(null, Page2));
        }
        //private void cbCalendarDisplay_CheckedChanged(object sender, EventArgs e)
        //{
            //刷新
            //LoadProvidersListData();
        //}

        #region 供应商清单及签单打印处理
        //private DataTable _dtProviderListData;
        /// <summary>
        /// 根据是否为日程显示娱乐的预订信息
        /// </summary>
        //private void LoadProvidersListData()
        //{
        //    if (cbCalendarDisplay.Checked == false)
        //    {
        //        _dtProviderListData = LocalTeamGroupCtrl.GetRestaurantOrderForProvider(lblTourGroupID.Text, _currentPageNumber, false);
        //        providerListGridControl.DataSource = _dtProviderListData;
        //    }
        //    else if (scheduleGridView.FocusedRowHandle >= 0)
        //    {
        //        string localPlanScheduleId = scheduleGridView.GetRowCellValue(scheduleGridView.FocusedRowHandle, "LocalPlanScheduleID").ToString();
        //        _dtProviderListData = LocalTeamGroupCtrl.GetRestaurantOrderForProvider(localPlanScheduleId, _currentPageNumber, true);
        //        providerListGridControl.DataSource = _dtProviderListData;
        //    }
        //    _dtProviderListData.ColumnChanged += new DataColumnChangeEventHandler(ProviderListData_ColumnChanged);

        //}

        #region 修改预订信息后的自动保存

        void ProviderListData_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            EntertainmenRestaurantOrderEntity entertainmentOrder = new EntertainmenRestaurantOrderEntity();
            
            entertainmentOrder.EntertainmentOrderID = int.Parse(e.Row["EntertainmentOrderID"].ToString());/*重点字段*/
            entertainmentOrder.ServiceName = e.Row["ServiceName"].ToString();
            entertainmentOrder.Remark = e.Row["Remark"].ToString();

            EntertainmenRestaurantOrderCtrl.UpdateEntertainmenRestaurantOrderPart( entertainmentOrder);

        }
        #endregion
  

        //private void tbSelectedAll_CheckedChanged(object sender, EventArgs e)
        //{
        //    foreach (DataRow dr in _dtProviderListData.Rows)
        //        dr["Selected"] = tbSelectedAll.Checked;
        //}

        #endregion

        #region 标签页显示
        private void tourGroupScheduleTabControl_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            switch (e.Page.Name)
            {
                //case "Page1"://日程
                //    LoadProvidersListData();
                //    break;
                case "Page2"://备注
                    memoEditRemark.Text = TeamGroupCtrl.GetTourGroupScheduleRemark(lblTourGroupID.Text);
                    break;
                case "Page3"://大计划
                    DataSet ds = TeamGroupCtrl.GetTourGroupSchedule(lblTourGroupID.Text);
                    if(ds.Tables.Count>0)
                    tourGroupScheduleGridControl.DataSource = ds.Tables[0]; 
                    break;
                default:
                    break;
            }
        }
        #endregion
        /// <summary>
        /// 变更通知
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChangeNotify_Click(object sender, EventArgs e)
        {
            ChangeNotifyForm changeNofityForm = new ChangeNotifyForm(lblTourGroupID.Text);
            changeNofityForm.ShowDialog(this);
        }

        private void tbOperationNumber_EditValueChanged(object sender, EventArgs e)
        {
            LocalTeamGroupCtrl.UpdateOperationNumberForTravel(lblTourGroupID.Text,tbOperationNumber.EditValue.ToString(), ApplicationHelper.CurrentLoginProviderNameAndID[1]);
        }

        #region 打钩选择处理

        /// <summary>
        /// 添加‘选择’附加列
        /// </summary>
        /// <param name="dtSource"></param>
        /// <returns></returns>
        //private DataTable AddGridSelectedColumn(DataTable dtSource)
        //{
        //    dtSource.Columns.Add("Selected", typeof(bool));
        //    return dtSource;
        //}

        //private void SelectedCheckEdit_CheckedChanged(object sender, EventArgs e)
        //{
        //    #region 打钩选择行

        //    int iFocuse = providerListGridView.FocusedRowHandle;
        //    providerListGridView.ClearSelection();

        //    if ((sender as CheckEdit).Checked)
        //        providerListGridView.SelectRow(iFocuse);

        //    int[] rowIds = MutilRow(providerListGridView);

        //    #endregion
        //}
        //private int[] MutilRow(GridView gv)
        //{
        //    object selected;
        //    for (int i = 0; i < gv.RowCount; i++)
        //    {
        //        selected = gv.GetRowCellValue(i, "Selected");

        //        if (string.IsNullOrEmpty(selected.ToString())) continue;

        //        if (Convert.ToBoolean(selected) == true)
        //        {
        //            gv.SelectRow(i);
        //        }
        //    }
        //    return gv.GetSelectedRows();
        //}

        #endregion

 
    }
}
